package com.example.basic.cmdprocess;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class InputStreamLineParser extends Thread {

	private static final String TAG = InputStreamLineParser.class.getName();

	private InputStream inputStream;
	private CountDownLatch countDownLatch;
	private List<String> result = new ArrayList<String>();
	private boolean print;
	private String[] breakStrings;

	InputStreamLineParser(InputStream inputStream, CountDownLatch countDownLatch, boolean print,
			String[] breakStrings) {
		this.inputStream = inputStream;
		this.countDownLatch = countDownLatch;
		this.print = print;
		this.breakStrings = breakStrings;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		String line = null;
		BufferedReader reader = null;
		try {
			if (inputStream == null) {
				return;
			}

			reader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));

			while (reader != null && (line = reader.readLine()) != null) {
				if (result != null && line.trim().length() > 0) {
					if (print) {
						System.out.println(TAG + "命令执行结果输出为：" + line);
					}
					synchronized (result) {
						result.add(line);
					}
				}
				if (isBreakString(line)) {
					break;
				}
				line = null;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				reader = null;
			}

		}

		if (countDownLatch != null) {
			countDownLatch.countDown();
		}
	}

	private boolean isBreakString(String line) {
		if (line != null) {
			if (line.contains(ProcessUtil.FAILED)) {
				return true;
			}
		} else {
			return false;
		}

		if (breakStrings == null || breakStrings.length == 0) {
			return false;
		}

		for (String breakString : breakStrings) {
			if (breakString != null && breakString.trim().length() > 0
					&&( (line.toUpperCase()).contains(breakString.toUpperCase()) || line.matches(breakString)  )) {
				return true;
			}
		}
		return false;
	}

	public List<String> getResult() {
		ArrayList<String> tmp = new ArrayList<>();
		synchronized (result) {
			tmp.addAll(result);
		}
		return tmp;
	}

}
